import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { ApiResponse } from '@/types';
import { getApiBaseUrl, getApiTimeout, getEnvConfig } from '@/utils/env';

// 创建axios实例
const createAxiosInstance = (): AxiosInstance => {
  const instance = axios.create({
    baseURL: getApiBaseUrl(),
    timeout: getApiTimeout(),
    headers: {
      'Content-Type': 'application/json',
    },
  });

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // 从localStorage获取token
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      
      // 添加时间戳防止缓存
      if (config.method === 'get') {
        config.params = {
          ...config.params,
          _t: Date.now(),
        };
      }
      
      // 根据环境决定是否打印请求日志
      const envConfig = getEnvConfig();
      if (envConfig.debug || envConfig.isDevelopment) {
        console.log('🚀 Request:', config);
      }
      return config;
    },
    (error) => {
      const envConfig = getEnvConfig();
      if (envConfig.debug || envConfig.isDevelopment) {
        console.error('❌ Request Error:', error);
      }
      return Promise.reject(error);
    }
  );

  // 响应拦截器
  instance.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      const envConfig = getEnvConfig();
      if (envConfig.debug || envConfig.isDevelopment) {
        console.log('✅ Response:', response);
      }
      
      // 统一处理响应
      const { data } = response;
      
      if (data.code === 200) {
        return response;
      } else {
        // 业务错误
        if (envConfig.debug || envConfig.isDevelopment) {
          console.error('❌ Business Error:', data.message);
        }
        return Promise.reject(new Error(data.message));
      }
    },
    (error) => {
      const envConfig = getEnvConfig();
      if (envConfig.debug || envConfig.isDevelopment) {
        console.error('❌ Response Error:', error);
      }
      
      // 处理HTTP错误
      if (error.response) {
        const { status, data } = error.response;
        
        switch (status) {
          case 401:
            // 未授权，清除token并跳转到登录页
            localStorage.removeItem('token');
            window.location.href = '/login';
            break;
          case 403:
            console.error('❌ 权限不足');
            break;
          case 404:
            console.error('❌ 请求的资源不存在');
            break;
          case 500:
            console.error('❌ 服务器内部错误');
            break;
          default:
            console.error('❌ 请求失败:', data?.message || error.message);
        }
      } else if (error.request) {
        console.error('❌ 网络错误，请检查网络连接');
      } else {
        console.error('❌ 请求配置错误:', error.message);
      }
      
      return Promise.reject(error);
    }
  );

  return instance;
};

// 导出axios实例
export const api = createAxiosInstance();

// 封装常用请求方法
export const request = {
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    api.get(url, config),
    
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    api.post(url, data, config),
    
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    api.put(url, data, config),
    
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    api.delete(url, config),
    
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse<ApiResponse<T>>> =>
    api.patch(url, data, config),
};
